#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QUrlQuery>
#include <QCryptographicHash>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMessageBox>
#include <QComboBox>
#include <QMap>
#include <QStringList>
#include <QKeyEvent>
#include "qxtglobalshortcut.h"

const QString TRANSLATE_API_ADDR = "http://api.fanyi.baidu.com/api/trans/vip/translate";
const QString APPID = "20200513000452399";
const QString SECRET_KEY = "GkBmo235pf5A96Sy1kpy";
const QString SALT = "1435660288";
const QMap<QString, QString> LANGUAGE_MAP = {
    {"自动检测", "auto"},
    {"中文", "zh"},
    {"英语", "en"},
    {"日语", "jp"},
};
const QStringList SRC_LANGUAGE_LIST = {"自动检测", "中文", "英语", "日语"};
const QStringList DST_LANGUAGE_LIST = {"中文", "英语", "日语"};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QObject::connect(ui->translate_btn, SIGNAL(clicked()), this, SLOT(OnTranslateBtnClicked()));
    QObject::connect(ui->swap_lan_btn, SIGNAL(clicked()), this, SLOT(OnSwapLanguageBtnClicked()));

    QxtGlobalShortcut *shortcut = new QxtGlobalShortcut(this);
    shortcut->setShortcut(QKeySequence("Ctrl+q"));
//    QObject::connect(shortcut, &QxtGlobalShortcut::activated, this, [&](){this->showNormal();});
    QObject::connect(shortcut, &QxtGlobalShortcut::activated, this, &MainWindow::SwitchWindowShow);

    InitLanguageComboBoxs();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::SwitchWindowShow()
{
    if (this->isMinimized())
    {
        this->showNormal();
    }
    else
    {
        this->showMinimized();
    }
}

void MainWindow::OnTranslateBtnClicked()
{
    TranslateText();
}

void MainWindow::TranslateText()
{
    QString text = ui->raw_text->toPlainText();
    QNetworkRequest request;
    QUrl qUrl = QUrl(TRANSLATE_API_ADDR);
    QUrlQuery urlQurey;
    urlQurey.addQueryItem("q", text);
    urlQurey.addQueryItem("from", GetCurSrcLanguage());
    urlQurey.addQueryItem("to", GetCurDstLanguage());
    urlQurey.addQueryItem("appid", APPID);
    urlQurey.addQueryItem("salt", SALT);
    QString str = QString("%1%2%3%4").arg(APPID).arg(text).arg(SALT).arg(SECRET_KEY);
    QByteArray ba;
    ba.append(str);
    QCryptographicHash md(QCryptographicHash::Md5);
    md.addData(ba);
    QString sign = QString(md.result().toHex());
    urlQurey.addQueryItem("sign", sign);
    qUrl.setQuery(urlQurey);

    request.setUrl(qUrl);
    QNetworkAccessManager *qnam = new QNetworkAccessManager(this);
    connect(qnam, SIGNAL(finished(QNetworkReply *)), this, SLOT(OnTranslateDataReturn(QNetworkReply *)));
    qnam->get(request);
}

QString MainWindow::GetCurSrcLanguage()
{
    QString language_name = ui->source_lan_list->currentText();
    if (LANGUAGE_MAP.contains(language_name))
        return LANGUAGE_MAP[language_name];
    return "";
}

QString MainWindow::GetCurDstLanguage()
{
    QString language_name = ui->dst_lan_list->currentText();
    if (LANGUAGE_MAP.contains(language_name))
        return LANGUAGE_MAP[language_name];
    return "";
}

void MainWindow::OnTranslateDataReturn(QNetworkReply * reply)
{
    QByteArray jsonData = reply->readAll();
    QString resultText = GetDestinationTextFromJson(jsonData);
    ui->result_txt->setText(resultText);
}

QString MainWindow::GetDestinationTextFromJson(QByteArray jsonData)
{
    QJsonParseError parseErr;
    QJsonDocument  rootDoc = QJsonDocument::fromJson(jsonData, &parseErr);//字符串格式化为JSON
    if (parseErr.error != QJsonParseError::NoError)
    {
        QMessageBox messageBox;
        messageBox.setWindowTitle("Error");
        messageBox.setText(QString("Json Parse Error: %0").arg(QString(jsonData)));
        messageBox.exec();
        return "";
    }
    QJsonObject rootObj = rootDoc.object();
    QString resultText = rootObj.value("trans_result").toArray().at(0).toObject().value("dst").toString();
    return resultText;
}

void MainWindow::OnSwapLanguageBtnClicked()
{
    SwapSrcDstLanguage();
}

void MainWindow::SwapSrcDstLanguage()
{
    QString src_lan = ui->source_lan_list->currentText();
    if (src_lan == "自动检测")
        src_lan = SRC_LANGUAGE_LIST[1];
    QString dst_lan = ui->dst_lan_list->currentText();
    ui->source_lan_list->setCurrentText(dst_lan);
    ui->dst_lan_list->setCurrentText(src_lan);
}

void MainWindow::InitLanguageComboBoxs()
{
    ui->source_lan_list->addItems(SRC_LANGUAGE_LIST);
    ui->dst_lan_list->addItems(DST_LANGUAGE_LIST);
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
#ifndef QT_NO_DEBUG
    qDebug() << "pressed key: " << static_cast<Qt::Key>(event->key()) << endl;
#endif
    if (event->modifiers() == Qt::ControlModifier)
    {
        if (event->key() == Qt::Key_Return)
            TranslateText();
        else if (event->key() == Qt::Key_I)
            SwapSrcDstLanguage();
    }
}
